<%@ page language="java" import="java.lang.*"  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
  <div class="widget-box" style="border:10px;margin:10px">
	<form id="baseInfor" style="width:870px;margin:10px auto;border-bottom: solid 2px #3b73af;">
	<div id="fromInfoContent" style="margin:10px auto;">
		<!-- 隐藏的入库计划主键 -->
  	        <input type="hidden" id="deliveryId" name="deliveryId" value="${delivery.deliveryId}">
  	        <input type="hidden" id="state" name="state" value="${delivery.state}">
  	        <div class="inline" style="margin-bottom:5px;">
  	        <label class="inline" for="deliveryNo" style="margin-right:20px;">
				装车发运编号：&nbsp;&nbsp;
				<input id="deliveryNo" name="deliveryNo" value="${delivery.deliveryNo}" placeholder="后台自动生成" readonly="readonly">
			</label>
			<label class="inline" for="customer" style="margin-right:20px;">
				客户(收货方)&nbsp;：<span class="field-required">*</span>
				<input id="customerId" name="customerId" style="width:210px" />
			</label>
			</div>
			<div class="inline" style="margin-bottom:5px;">
			<label class="inline" for="outOrder" style="margin-right:20px;" >
				出库单选择&emsp;：<span class="field-required">*</span>
				<input id="outOrderId" name="outOrderId" style="width:210px;">
			</label>
			</div>
			<div class="inline" style="margin-bottom:5px;">
			   <label class="inline" for="inPlanTime" style="margin-right:20px;">
				装车发运时间：<span class="field-required">*</span>
				<div class="inline" style="width: 200px;vertical-align:middle;">
					<div class="input-group">
						<input class="form-control date-picker" id="deliveryDate" name="deliveryDate" style="width: 200px;" type="text" value="${delivery.deliveryDate}"
						 placeholder="装车发运时间"/>
						<span class="input-group-addon">
							<i class="fa fa-calendar bigger-110"></i>
						</span>
					</div>
				</div>
				
			</label>
			</div></br>
			<div class="inline" style="margin-bottom:5px;">
  	        <label class="inline" for="packageNo" style="margin-right:20px;">
				包装箱编号&emsp;：&nbsp;&nbsp;
				<input id="packageNo" name="packageNo" value="${delivery.packageNo}" placeholder="包装箱编号">
			</label>
			<label class="inline" for="packageNo" style="margin-right:20px;">
				车辆信息&emsp;&emsp;：&nbsp;&nbsp;
				<input id="car" name="car" value="${delivery.car}" placeholder="车辆信息">
			</label>
			</div>
			<div class="inline" style="margin-bottom:5px;">
  	        <label class="inline" for="customer" style="margin-right:20px;">
				备&emsp;&emsp;&emsp;&emsp;注：&nbsp;&nbsp;
				<input id="remark" name="remark" value="${delivery.remark}" placeholder="备注">
			</label>
			</div>
		</div>
	<div style="margin-bottom:5px;">
		<div class="btn btn-xs btn-primary" id="formSave">保存</div>
		<div class="btn btn-xs btn-primary" id="formSubmit">提交</div>
	</div>
	</form>
	<div id="materialDiv" style="margin:10px;">
		<!-- 下拉框 -->
		<label class="inline" for="materialInfor">物料：</label>
		<input type="text" id = "materialInfor" name="materialInfor" 
		style="width:350px;margin-right:10px;" />
		<button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
			<i class="icon-plus" style="margin-right:6px;"></i>添加
		</button>
	</div>
	<!-- 表格div -->
	<div id="grid-div-c" style="width:100%;margin:10px auto;">
		<!-- 隐藏区域：存放查询条件 -->
		<!-- 	表格工具栏 -->
        <div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
             <div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
        </div>
		<!-- 物料详情信息表格 -->
		<table id="grid-table-c" style="width:100%;height:100%;"></table>
		<!-- 表格分页栏 -->
		<div id="grid-pager-c"></div>
	</div>
</div>
<script type="text/javascript">
var context_path = '<%=path%>';
var deliveryId=$("#deliveryId").val();
var oriDataDetail;
 var _grid_detail;        //表格对象
 var lastsel2;
 $(".date-picker").datetimepicker({format: 'YYYY-MM-DD HH:mm:ss',useMinutes:true,useSeconds:true});
$("#baseInfor").validate({
   ignore: "", 
   rules:{
      <%-- "customer":{
         remote:{
            cache:false,
            async:false,
            url: "<%=path%>/delivery/isHaveName?deliveryId="+$('#deliveryId').val()
         }
      }, --%>
      
      "customerId":{
         required:true,
      },
      "outOrderId":{
         required:true,
      },
      "deliveryDate":{
         required:true,
      },
   },
   messages: {
       "customerId":{
         required:"请选择客户！",
      },
      "outOrderId":{
         required:"请选择出库单！"
      },
      "deliveryDate":{
         required:"请选择装车发运时间！",
      },
      
   },
   errorPlacement: function (error, element) {
       layer.msg(error.html(),{icon:5});
       }
});



$("#formSubmit").click(function(){
  if($("#deliveryId").val()==""){
    layer.msg("请先保存表头信息！",{icon:2,time:1200});
    return;
  }
   $.ajax({
   url:context_path+"/delivery/submit?deliveryId="+$("#deliveryId").val(),
   type:"post",
   dataType:"JSON",
   success:function (data){
      if(data.result){
      layer.msg(data.msg,{icon:1,time:1200});
      gridReload();
      }else{
      layer.msg(data.msg,{icon:2,time:1200});
      }
   }
   });
});
$("#formSave").click(function(){

  var bean = $("#baseInfor").serialize();
if($('#baseInfor').valid()){
   saveOrUpdate(bean);
} 
});

/* 保存、修改 */
function saveOrUpdate(bean){
   $.ajax({
   url:context_path+"/delivery/save",
   type:"post",
   data:bean,
   dataType:"JSON",
   success:function (data){
      if(data.result){
      $("#deliveryId").val(data.deliveryId);
      $("#baseInfor #deliveryNo").val(data.deliveryNo);
      deliveryId=data.deliveryId;
      gridReload();
       $("#grid-table-c").jqGrid('setGridParam', 
           	{
              url : context_path + '/delivery/detailList?deliveryId='+deliveryId,
               postData: {queryJsonString:""} //发送数据  :选中的节点
             } ).trigger("reloadGrid");
      layer.msg("操作成功！",{icon:1,time:1200});
      }else{
      layer.msg("操作失败！",{icon:2,time:1200});
      }
   }
   });

}
//单元格编辑成功后，回调的函数
	var editFunction = function eidtSuccess(XHR){
		 var data = eval("("+XHR.responseText+")"); 
		if(data["msg"]!=""){
			layer.alert(data["msg"]);
		}
		jQuery("#grid-table-c").jqGrid('setGridParam', 
				{
					postData: {
						id:$('#id').val(),
						queryJsonString:""
					} 
				}
		  ).trigger("reloadGrid");
	};
	
  
  	_grid_detail=jQuery("#grid-table-c").jqGrid({
         url : context_path + '/delivery/detailList?deliveryId='+deliveryId,
         datatype : "json",
         colNames : [ '详情主键','物料编号','物料名称','数量',],
         colModel : [ 
  					  {name : 'id',index : 'id',width : 20,hidden:true}, 
  					  {name : 'materialNo',index:'materialNo',width :20}, 
                      {name : 'materialName',index:'materialName',width : 20}, 
                      //{name : 'amount',index:'amount',width : 20,editable : true,editrules: {custom: true, custom_func: numberRegex}},
                      {name: 'amount', index: 'amount', width: 60,editable : true,editrules: {custom: true, custom_func: numberRegex},
                        editoptions: {
	                          size: 25,
	                          dataEvents: [
	                              {
	                                  type: 'blur',     //blur,focus,change.............
	                                  fn: function (e) {
	                                	  var $element = e.currentTarget;
	                                	  var $elementId = $element.id;
	                                	  var rowid = $elementId.split("_")[0];
	                                	  var id=$element.parentElement.parentElement.children[1].textContent;
	                                	  var indocType = 1;
	                                	 // var rowData = $("#grid-table-c").jqGrid('getRowData',rowid).id;
	                                		  var reg = new RegExp("^[0-9]+(.[0-9]{1,2})?$");
	                                		  if (!reg.test($("#"+$elementId).val())) {
	                                			  layer.alert("非法的数量！(注：可以有两位小数的正实数)");
	                                			  return;
	                                		  }
	                                	  $.ajax({
	                                		  url:context_path + '/delivery/updateAmount',
	                                		  type:"POST",
	                                		  data:{id:id,amount:$("#"+rowid+"_amount").val()},
	                                		  dataType:"json",
	                                		  success:function(data){
	                                		        if(!data.result){
	                                		           layer.alert(data.msg);
	                                		        }
	                                		        $("#grid-table-c").jqGrid('setGridParam', 
                                							{
                                					    		url : context_path + '/delivery/detailList?deliveryId='+deliveryId,
                                								postData: {queryJsonString:""} //发送数据  :选中的节点
                                							}
                                					  ).trigger("reloadGrid");
	                                		      
	                                		  }
	                                	  }); 
	                                  }
	                              }
	                          ]
	                      }
                      },
                    ],
         rowNum : 20,
         rowList : [ 10, 20, 30 ],
         pager : '#grid-pager-c',
         sortname : 'ID',
         sortorder : "asc",
         altRows: true,
         viewrecords : true,
         caption : "物料列表",
         autowidth:true,
         multiselect:true,
		 multiboxonly: true,
         loadComplete : function(data) 
         {
             var table = this;
             setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
             oriDataDetail = data;
         },
       /* cellurl : context_path + "/delivery/updateAmount", */
	   cellEdit: true,
	   cellsubmit : "clientArray",
  	   emptyrecords: "没有相关记录",
  	   loadtext: "加载中...",
  	   pgtext : "页码 {0} / {1}页",
  	   recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#grid-table-c").navGrid('#grid-pager-c',{edit:false,add:false,del:false,search:false,refresh:false})
      .navButtonAdd('#grid-pager-c',{  
  	   caption:"",   
  	   buttonicon:"ace-icon fa fa-refresh green",   
  	   onClickButton: function(){   
  	    $("#grid-table-c").jqGrid('setGridParam', 
				{
  	    			url:context_path + '/delivery/detailList?deliveryId='+deliveryId,
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
  	   }
  	});
  	
  	$(window).on('resize.jqGrid', function () {
  		$("#grid-table-c").jqGrid( 'setGridWidth', $("#grid-div-c").width() - 3 );
  		$("#grid-table-c").jqGrid( 'setGridHeight', (document.documentElement.clientHeight - $("#grid-pager-c").height() - 380) );
  	});
  	$(window).triggerHandler('resize.jqGrid');
  	if($("#id").val()!=""){
  		//reloadDetailTableList();   //重新加载详情列表
  	}
function reloadDetailTableList(){   //重新加载详情列表
      $("#grid-table-c").jqGrid('setGridParam', 
				{
  	    			url:context_path + '/delivery/detailList?deliveryId='+deliveryId,
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
  }
//将数据格式化成两位小数：四舍五入
 function formatterNumToFixed(value,options,rowObj){
	if(value!=null){
		var floatNum = parseFloat(value);
		return floatNum.toFixed(2);
	}else{
		return "0.00";
	}
 } 
 //数量输入验证
function numberRegex(value, colname) {
    var regex = /^\d+\.?\d{0,2}$/;
    reloadDetailTableList();
    if (!regex.test(value)) {
        return [false, ""];
    }
    else  return [true, ""];
}


     $('#materialInfor').select2({
			placeholder : "请选择物料",//文本框的提示信息
			minimumInputLength : 0, //至少输入n个字符，才去加载数据
			allowClear : true, //是否允许用户清除文本信息
			multiple: true,
			closeOnSelect:false,
			ajax : {
				url : context_path + '/delivery/getMListByInId',
				dataType : 'json',
				delay : 250,
				data : function(term, pageNo) { //在查询时向服务器端传输的数据
					term = $.trim(term);
					selectParam = term;
					return {
						/* docId : $("#baseInfor #id").val(), */
						queryString : term, //联动查询的字符
						pageSize : 15, //一次性加载的数据条数
						pageNo : pageNo, //页码
						time : new Date(),
						deliveryId:$("#deliveryId").val()
					//测试
					}
				},
				results : function(data, pageNo) {
					var res = data.result;
					if (res.length > 0) { //如果没有查询到数据，将会返回空串
						var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
						return {
							results : res,
							more : more
						};
					} else {
						return {
							results : {
								"id" : "0",
								"text" : "没有更多结果"
							}
						};
					}

				},
				cache : true
			}
		});

		$('#materialInfor').on("change",function(e){
			var datas=$("#materialInfor").select2("val");
			selectData = datas;
			var selectSize = datas.length;
			if(selectSize>1){
				var $tags = $("#s2id_materialInfor .select2-choices");   //
				//$("#s2id_materialInfor").html(selectSize+"个被选中");
				var $choicelist = $tags.find(".select2-search-choice");
				var $clonedChoice = $choicelist[0];
				$tags.children(".select2-search-choice").remove();
				$tags.prepend($clonedChoice);
				
				$tags.find(".select2-search-choice").find("div").html(selectSize+"个被选中");
				$tags.find(".select2-search-choice").find("a").removeAttr("tabindex");
				$tags.find(".select2-search-choice").find("a").attr("href","#");
				$tags.find(".select2-search-choice").find("a").attr("onclick","removeChoice();");
			}
			//执行select的查询方法
			$("#materialInfor").select2("search",selectParam);
		});
		

if($("#baseInfor #deliveryId").val()!=""){

  
   
     $.ajax({
			  type:"POST",
			  url:context_path + '/delivery/getDelivery',
			  data:{deliveryId:$('#baseInfor #deliveryId').val()},
			  dataType:"json",
			  success:function(data){
			     $("#baseInfor #customerId").select2("data", {
				   id: data.delivery.customerId,
				   text: data.delivery.customerName
				  }); 
				  $("#baseInfor #outOrderId").select2("data", {
				   id: data.delivery.outOrderId,
				   text: data.delivery.outNO
				  }); 
			  }
			  });
   
}else{

}
 //清空物料多选框中的值
 function removeChoice(){
	  $("#s2id_materialInfor .select2-choices").children(".select2-search-choice").remove();
	  $("#materialInfor").select2("val","");
	  selectData = 0;
	  
 }

//添加物料详情
 function addDetail(){
	  if($("#deliveryId").val()==""){
		  layer.alert("请先保存表单信息！");
		  return;
	  }
	  if(selectData!=0){
		  //将选中的物料添加到数据库中
		  $.ajax({
			  type:"POST",
			  url:context_path + '/delivery/saveDetail',
			  data:{deliveryId:$('#baseInfor #deliveryId').val(),detailIds:selectData.toString()},
			  dataType:"json",
			  success:function(data){
				  removeChoice();   //清空下拉框中的值
				  if(Boolean(data.result)){
						layer.msg("添加成功",{icon:1,time:1200});
					  //重新加载详情表格
					  $("#grid-table-c").jqGrid('setGridParam', 
							{
								postData: {deliveryId:$("#baseInfor #deliveryId").val()} //发送数据  :选中的节点
							}
					  ).trigger("reloadGrid");
				  }else{
					  layer.msg(data.msg,{icon:2,time:1200});
				  }
			  }
		  });
	  }else{
		  layer.alert("请选择物料！");
	  }
  }
  //工具栏
	  $("#__toolbar__-c").iToolBar({
	   	 id:"__tb__01",
	   	 items:[
	   	  	{label:"删除", onclick:delDetail},
	    ]
	  });
	//删除物料详情
	function delDetail(){
	   var ids = jQuery("#grid-table-c").jqGrid('getGridParam', 'selarrrow');
	   $.ajax({
	      url:context_path + '/delivery/deleteDetail?ids='+ids,
	      type:"POST",
	      dataType:"JSON",
	      success:function(data){
	         if(data.result){
	           layer.msg("操作成功！");
	            //重新加载详情表格
					  $("#grid-table-c").jqGrid('setGridParam', 
							{
								postData: {deliveryId:$("#baseInfor #deliveryId").val()} //发送数据  :选中的节点
							}
					  ).trigger("reloadGrid");
	         }
	      }
	   });
	}
	
	
	
	$("#baseInfor #customerId").select2({
        placeholder: "请选择收货方",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        multiple: true,
        ajax: {
            url: context_path + "/salemanage/getSelectCusom",
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date(),
                   // stuffId: shelveId
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
	
	$("#baseInfor #outOrderId").select2({
        placeholder: "请选择出库单",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        multiple: true,
        ajax: {
            url : context_path + '/delivery/getSelectOut',
            type: "POST",
            dataType: 'json',
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date(),
                   // stuffId: shelveId
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
  </script>
